package com.web.controller;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.web.model.ResponseData;

import cn.hutool.core.io.FileUtil;

@RestController
@RequestMapping("/upload")
public class UploadController {

	@PostMapping
	public ResponseData upload(MultipartFile file,HttpServletRequest req) throws IOException{
				
		String fileName = file.getOriginalFilename();
		InputStream is = file.getInputStream();
		String[] split = fileName.split("\\.");
		int length = split.length;
		int finalIndex = length-1;
		String suffix = split[finalIndex];
		fileName = System.currentTimeMillis() +"."+suffix;
		String tomcatPath ="/www/server/tomcat_site/43.142.87.163/photo";
		String fullPath = tomcatPath+"/"+fileName;
		FileUtil.writeFromStream(is, fullPath);
		String http =req.getScheme();
		String localhost = req.getServerName();
		int port = req.getServerPort();
		String url = http+"://"+localhost+":"+port+"/photo/"+fileName;
		ResponseData responseData = new ResponseData();
		responseData.success("上传成功",url);
		return responseData;
	}
}